<template>
  <div style="position: fixed;top: 0;left: 0;right: 0;z-index: 1000;">
    <TopNavBar :title="_t18('13_loan1')" />
  </div>
  <div style="height: 50px;"></div>

  <!-- ✅ 下拉刷新区域 -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <div class="borrowing-currency-page">
      <!-- 顶部卡片区域 -->
      <div class="top-card">
        <div class="top-card-content">
          <div class="title">{{ _t18('13_loan1') }}</div>
          <div class="desc">{{ _t18('13_loan2') }}</div>
          <div class="features">
            <div class="feature-item">
              <img src="@/assets/defi/yes.png" class="feature-icon" />
              {{ _t18('13_loan3') }}
            </div>
            <div class="feature-item">
              <img src="@/assets/defi/yes.png" class="feature-icon" />
              {{ _t18('13_loan4') }}
            </div>
            <div class="feature-item">
              <img src="@/assets/defi/yes.png" class="feature-icon" />
              {{ _t18('13_loan5') }}
            </div>
          </div>
        </div>
        <img class="top-card-icon" src="/static/img/frv_e94cb34b_uEa.cf090d90.png" />
      </div>

      <!-- 金额模块 -->
      <div class="amount-section" style="position: relative;">
        <img style="z-index: 1; position: absolute;top: 0;height: 100%;" class="amount-left-bg" src="@/assets/defi/lefbg.png" />
        <div class="amount-left" style="position: relative;">
          <div style="display: flex;align-items: center;justify-content: center;">
            <img class="amount-left-icon" src="@/assets/defi/lef.png" />
            <div style="margin-left: 10px;" class="amount-label">{{ _t18('13_loan6') }}</div>
          </div>
          <div class="amount-value">{{ totalLoan }} USD</div>
        </div>

        <div class="amount-right">
          <div style="display: flex;align-items: center;justify-content: center;">
            <img class="amount-right-icon" src="@/assets/defi/rig.png" />
            <div style="margin-left: 10px;" class="amount-label">{{ _t18('13_loan7') }}</div>
          </div>
          <div class="amount-value">{{ reLoan }} USD</div>
        </div>
      </div>

      <!-- 底部按钮区 -->
      <div class="bottom-actions">
        <button class="action-btn">
          <div class="icon-placeholder" style="width:28px;height:28px;border-radius:6px;"></div>
          {{ _t18('13_loan8') }}
          <img src="/static/img/N7z_dd8b4091_CEz.a908c6bc.svg" alt="">
        </button>
        <button class="action-btn" @click="orderLog">
          <div class="icon-placeholder" style="width:28px;height:28px;border-radius:6px;"></div>
          {{ _t18('13_loan9') }}
          <img src="/static/img/N7z_dd8b4091_CEz.a908c6bc.svg" alt="">
        </button>
      </div>

      <!-- 表单区 -->
      <div class="form-section">
        <div v-if="step === 1">
          <div class="form-label">{{ _t18('13_loan10') }}</div>
          <div class="input-group">
            <button class="input-max">MAX</button>
            <input class="input-amount" type="text" disabled v-model="productDetail.amountMax" />
            <span class="input-currency">
              <img src="/static/no-rename/usd.png" class="input-currency-icon" />
              <span>USD</span>
            </span>
          </div>

          <div class="form-label">{{ _t18('13_loan11') }}</div>
          <div class="input-group">
            <input class="input-amount" type="number" v-model="amount" :min="productDetail.amountMin" />
            <span class="input-currency">
              <img src="/static/no-rename/usd.png" class="input-currency-icon" />
              <span>USD</span>
            </span>
          </div>

          <div class="form-label">{{ _t18('13_loan12') }}</div>
          <div class="term-group">
            <button
              v-for="term in repaymentCycle"
              :key="term.value"
              class="term-btn"
              :class="{ active: productDetail.value === term.value }"
              @click="selectTerm(term)"
            >
              {{ term.name }} {{ _t18('13_loan13') }}
            </button>
          </div>

          <div class="fee-card">
            <div class="fee-row"><span>{{ _t18('13_loan14') }}</span><span>{{ productDetail.odds }}%</span></div>
            <div class="fee-row"><span>{{ _t18('13_loan15') }}</span><span>{{ (Number(amount) * Number(productDetail.odds) / 100).toFixed(5) }} USD</span></div>
            <div class="fee-row"><span>{{ _t18('13_loan16') }}</span><span>{{ Number(productDetail.name * productDetail.odds * amount / 100).toFixed(5) }} USD</span></div>
            <div class="fee-row"><span class="fee-green">{{ _t18('13_loan17') }}</span><span class="fee-green">{{ Number(amount) + Number(amount * productDetail.odds * productDetail.name / 100) }}USD</span></div>
          </div>

          <div class="form-check">
            <input type="checkbox" id="agree" v-model="agree" />
            <label for="agree">{{ _t18('13_loan18') }}</label>
          </div>

          <button class="form-btn" @click="nextStep">{{ _t18('13_loan19') }}</button>
        </div>

        <div v-if="step === 2">
          <div class="form-label">{{ _t18('13_loan20') }} <span class="hui">({{ _t18('13_loan21') }})</span></div>
          <div class="bottom">
            <div class="upload-box">
              <div class="item">
                <van-uploader :after-read="afterRead1" v-model="fileList1">
                  <img src="@/assets/defi/delete.png" alt="" class="img" />
                  <div class="tit">{{ _t18('13_loan22') }}</div>
                </van-uploader>
              </div>
              <div class="item">
                <van-uploader :after-read="afterRead2" v-model="fileList2">
                  <img src="@/assets/defi/delete.png" alt="" class="img" />
                  <div class="tit">{{ _t18('13_loan23') }}</div>
                </van-uploader>
              </div>
              <div class="item">
                <van-uploader :after-read="afterRead3" v-model="fileList3">
                  <img src="@/assets/defi/delete.png" alt="" class="img" />
                  <div class="tit">{{ _t18('13_loan24') }}</div>
                </van-uploader>
              </div>
            </div>
            <button class="form-btn" @click="submit">{{ _t18('13_loan25') }}</button>
          </div>
        </div>
      </div>
    </div>
  </van-pull-refresh>

  <div style="height: 100px;"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getLoanProductList, getLoan, getLoanOrderList } from '@/api/loan.js'
import { _t18 } from '@/utils/public'
import { uploadImg } from '@/api/common/index.js'
import { showToast } from 'vant'
import { useToast } from '@/hook/useToast'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const { _toast } = useToast()
const { t } = useI18n()
const router = useRouter()

const agree = ref(true)
const amount = ref(0.0)
const step = ref(1)
const repaymentCycle = ref([])
const productDetail = ref({})
const fileList1 = ref([])
const fileList2 = ref([])
const fileList3 = ref([])
const totalLoan = ref(0.0)
const reLoan = ref(0.0)
const refreshing = ref(false)

// ✅ 下拉刷新（有多语言提示）
const onRefresh = async () => {
  refreshing.value = true
  try {
    await Promise.all([getProductList(), getList()])
    showToast(t('recharge_tab_success')) // ✅ 成功提示
  } catch (e) {
    showToast(t('recharge_tab_error')) // ✅ 失败提示
  } finally {
    setTimeout(() => {
      refreshing.value = false
    }, 800)
  }
}

// 上传逻辑保持不变
const afterRead1 = (file) => {
  file.status = 'uploading'
  const formData = new FormData()
  formData.append('file', file.file)
  uploadImg(formData).then((res) => {
    res = res.data
    if (res.code == '200') {
      file.res = res.data.url
      file.status = 'success'
    } else {
      showToast(res.msg)
      fileList1.value = []
    }
  })
}
const afterRead2 = (file) => {
  file.status = 'uploading'
  const formData = new FormData()
  formData.append('file', file.file)
  uploadImg(formData).then((res) => {
    res = res.data
    if (res.code == '200') {
      file.res = res.data.url
      file.status = 'success'
    } else {
      showToast(res.msg)
      fileList2.value = []
    }
  })
}
const afterRead3 = (file) => {
  file.status = 'uploading'
  const formData = new FormData()
  formData.append('file', file.file)
  uploadImg(formData).then((res) => {
    res = res.data
    if (res.code == '200') {
      file.res = res.data.url
      file.status = 'success'
    } else {
      showToast(res.msg)
      fileList3.value = []
    }
  })
}

// 原功能保留
const nextStep = () => { step.value = step.value === 1 ? 2 : 1 }
const selectTerm = (term) => { productDetail.value = term }

const getProductList = async () => {
  const res = await getLoanProductList()
  if (res.code == '200') {
    repaymentCycle.value = res.rows.map((elem, index) => ({
      id: index,
      name: elem.cycleType,
      value: elem.id,
      amountMin: elem.amountMin,
      amountMax: elem.amountMax,
      odds: elem.odds
    }))
    selectorAction(repaymentCycle.value[0])
  }
}

const selectorAction = (item) => { productDetail.value = item }

const submit = () => {
  if (
    amount.value == '' ||
    amount.value > productDetail.value.amountMax ||
    amount.value < productDetail.value.amountMin
  ) {
    _toast(`loan_amountErr`)
    return
  }
  if (fileList1.value.length == 0) {
    _toast(`loan_idcardFront`)
    return
  }
  if (fileList2.value.length == 0) {
    _toast(`loan_idcardReverse`)
    return
  }
  if (fileList3.value.length == 0) {
    _toast(`loan_hand`)
    return
  }
  const file1 = fileList1.value[0] || {}
  const file2 = fileList2.value[0] || {}
  const file3 = fileList3.value[0] || {}
  getLoan({
    proId: productDetail.value.value,
    cycleType: productDetail.value.name,
    cardUrl: file1.res,
    cardBackUrl: file2.res,
    capitalUrl: file3.res,
    amount: amount.value
  }).then((res) => {
    if (res.code == '200') {
      _toast(`loan_applySuccess`)
      setTimeout(() => {
        router.push('/loan-record')
      }, 500)
    } else {
      showToast(res.msg)
    }
  })
}

const orderLog = () => { router.push('/loan-record') }

const getList = () => {
  let params = `pageNum=1&pageSize=500`
  getLoanOrderList(params).then((res) => {
    if (res.code == '200') {
      totalLoan.value = 0
      reLoan.value = 0
      res.rows.forEach((row) => {
        totalLoan.value += Number(row.amount)
        if (row.status == 1) reLoan.value += Number(row.amount)
      })
    } else {
      showToast(res.msg)
    }
  })
}

onMounted(async () => {
  await getProductList()
  getList()
})
</script>


<style scoped>
:deep(.van-uploader__wrapper) {
            width: 100%;
            height: 100%;
            display: block;

            .van-uploader__input-wrapper {
              display: flex;
              flex-direction: column;
              align-items: center;
            }

            .van-uploader__preview {
              width: 100%;
              height: 100%;
              margin: auto;

              .van-uploader__preview-image {
                width: 100%;
                height: 194px;
              }
            }

            .van-uploader__preview-delete {
              width: 20px;
              height: 20px;

              .van-uploader__preview-delete-icon {
                font-size: 22px;
              }
            }
          }
.borrowing-currency-page {
  background: #f5f6fa;
  min-height: 100vh;
  padding: 18px 0 0 0;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.top-card {
  background: #f9cf6a;
  border-radius: 22px;
  padding: 28px 28px 18px 28px;
  position: relative;
  margin: 0 12px 18px 12px;
  overflow: hidden;
  min-height: 140px;
}
.top-card-content {
  z-index: 1;
  position: relative;
}
.title {
  font-size: 22px;
  font-weight: 700;
  color: #222;
  margin-bottom: 10px;
}
.desc {
  font-size: 13px;
  color: #222;
  font-weight: 500;
  margin-bottom: 18px;
}
.features {
  display: flex;
  gap: 22px;
}
.feature-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #222;
  font-weight: 600;
}
.feature-icon {
  width: 22px;
  height: 22px;
  margin-right: 6px;
}
.top-card-icon {
  width: 68px;
  height: 68px;
  position: absolute;
  top: 18px;
  right: 18px;
  z-index: 2;
}

.amount-section {
  display: flex;
  border-radius: 20px;
  margin: 0 12px 18px 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  background: #fff;
}
.amount-left {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  padding: 19px 0 19px 24px;
}
 
.amount-left-icon {
  width: 28px;
  height: 28px;
  margin-bottom: 8px;
  z-index: 1;
}
.amount-label {
  font-size: 12px;
  color: #e0dfff;
  margin-bottom: 6px;
  z-index: 1;
  font-weight: 500;
}
.amount-value {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  z-index: 1;
}
.amount-left .amount-label {
  color: #e0dfff;
}
.amount-left .amount-value {
  color: #fff;
}
.amount-right {
  flex: 1;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  padding: 19px 0 19px 24px;
  min-width: 0;
}
.amount-right-icon {
  width: 28px;
  height: 28px;
  margin-bottom: 8px;
}
.amount-right .amount-label {
  color: #888;
  font-weight: 500;
  font-size: 12px;
}
.amount-right .amount-value {
  color: #222;
  font-size: 18px;
  font-weight: bold;
}

.bottom-actions {
  display: flex;
  gap: 16px;
  margin: 0 12px 0 12px;
}
.action-btn {
  flex: 1;
  background: #111;
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 0;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 14px;
  height: 56px;
  position: relative;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  margin-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 22px;
}
.action-btn:active {
  background: #222;
}
.icon-placeholder {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}
.action-btn span {
  flex: 1;
  text-align: left;
}
 
.form-section {
  background: none;
  margin: 0 0 0 0;
  padding: 0 0 24px 0;
}
.form-label {
  font-size: 13px;
  font-weight: 600;
  color: #111;
  margin: 18px 0 8px 12px;
}
.input-group {
  background: #fff;
  border-radius: 14px;
  display: flex;
  align-items: center;
  position: relative;
  margin: 0 12px 12px 12px;
  padding: 0 12px;
  height: 48px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.03);
}
.input-status {
  font-size: 12px;
  font-weight: 600;
  color: #f44;
  background: #ffeaea;
  border-radius: 8px;
  padding: 2px 10px;
  margin-right: 8px;
}
.input-status.fail {
  color: #f44;
  background: #ffeaea;
}
.input-max {
  font-size: 12px;
  color: #222;
  background: #f5f6fa;
  border: none;
  border-radius: 8px;
  padding: 2px 10px;
  margin-right: 8px;
  font-weight: 600;
  cursor: pointer;
}
.input-amount {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 15px;
  color: #222;
  outline: none;
  font-weight: 600;
  min-width: 0;
}
.input-currency {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #4b2ff9;
  font-weight: 700;
  margin-left: 6px;
  span{
    margin-top: 2px;
  }
}
.input-currency-icon {
  width: 24px;
  height: 24px;
  margin-right: 5px;
}
.term-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0 12px 12px 12px;
}
.term-btn {
  flex: 1 1 28%;
  min-width: 70px;
  background: #fff;
  color: #222;
  border: none;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  padding: 10px 0;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.term-btn.active {
  background: #111;
  color: #fff;
}
.fee-card {
  background: #fff;
  border-radius: 16px;
  margin: 0 12px 12px 12px;
  padding: 16px 16px 8px 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  line-height: 30px;
}
.fee-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: #222;
  margin-bottom: 8px;
}
.fee-row:last-child {
  margin-bottom: 0;
}
.fee-green {
  color: #00b96b;
  font-weight: 700;
}
.fee-tip {
  font-size: 12px;
  color: #aaa;
  margin-left: 2px;
}
.form-check {
  display: flex;
  align-items: center;
  margin: 0 12px 18px 12px;
  font-size: 13px;
}
.form-check input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin-right: 6px;
  accent-color: #4b2ff9;
}
.form-check label {
  color: #222;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
}
.form-btn {
  width: calc(100% - 24px);
  margin: 0 12px;
  height: 48px;
  background: #111;
  color: #fff;
  border: none;
  border-radius: 14px;
  font-size: 15px;
  font-weight: 700;
  letter-spacing: 2px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  cursor: pointer;
  transition: background 0.2s;
}
.form-btn:active {
  background: #222;
}

.bottom {
    /* padding: 0 15px; */
  background: #fff;
  border-radius: 16px;
  margin: 0 12px 12px 12px;
  padding: 16px 16px 8px 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  line-height: 30px;

    .upload {
      margin: 30px 0 10px 0;

      .photo {
        font-size: 14px;
        color: var(--ex-default-font-color);
      }

      span {
        font-size: 14px;
        color: var(--ex-passive-font-color);
      }
    }

    .upload-box {
      .item {
        height: 194px;
        background: #fff;
        border-radius: 3px;
        /* border: 1px solid var(--ex-border-color1); */
        margin-bottom: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;

        .van-uploader {
          width: 100%;

          
        }

        .img {
          width: 50px;
          height: 50px;
          min-width: none;
          min-height: none;
          object-fit: contain;
          margin: 50px 0 20px 0;
        }

        .tit {
          box-sizing: border-box;
          width: 100%;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: 400;
          color: var(--ex-passive-font-color);
        }
      }
    }

    .btn {
      font-size: 14px;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 50px;
      background: var(--ex-div-bgColor1);
      border-radius: 3px;
      color: var(--ex-font-color);
      margin: 50px 0;
    }
  }
</style> 